package pdf;

import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class MarkdownToPdfConverter {

    /**
     * 将Markdown文件转换为PDF文件
     *
     * @param markdownFilePath Markdown文件路径
     * @param pdfFilePath      输出的PDF文件路径
     * @throws Exception 转换过程中可能出现的异常
     */
    public static void convert(String markdownFilePath, String pdfFilePath) throws Exception {
        // 1. 读取Markdown文件内容
        String markdownContent = readFile(markdownFilePath);

        // 2. 将Markdown转换为HTML
        String htmlContent = convertMarkdownToHtml(markdownContent);

        // 添加基本的HTML包装和样式
        String fullHtml = wrapHtmlWithStyle(htmlContent);

        // 3. 将HTML转换为PDF
        convertHtmlToPdf(fullHtml, pdfFilePath);
    }

    /**
     * 读取文件内容
     */
    private static String readFile(String filePath) throws IOException {
        byte[] bytes = Files.readAllBytes(Paths.get(filePath));
        return new String(bytes, StandardCharsets.UTF_8);
    }

    /**
     * 将Markdown转换为HTML
     */
    private static String convertMarkdownToHtml(String markdown) {
        Parser parser = Parser.builder().build();
        Node document = parser.parse(markdown);
        HtmlRenderer renderer = HtmlRenderer.builder().build();
        return renderer.render(document);
    }

    /**
     * 为HTML添加基本样式和完整结构
     */
    private static String wrapHtmlWithStyle(String htmlContent) {
        return "<!DOCTYPE html>\n" +
                "<html>\n" +
                "<head>\n" +
                "<meta charset=\"UTF-8\">\n" +
                "<style>\n" +
                "body { font-family: SimSun, \"宋体\", serif; line-height: 1.6; padding: 20px; }\n" +
                "h1, h2, h3 { color: #333; border-bottom: 1px solid #eee; padding-bottom: 0.3em; }\n" +
                "pre { background-color: #f8f8f8; padding: 1em; border-radius: 4px; overflow: auto; }\n" +
                "code { font-family: Consolas, monospace; }\n" +
                "blockquote { border-left: 4px solid #ddd; padding: 0 15px; color: #777; }\n" +
                "table { border-collapse: collapse; margin: 1em 0; }\n" +
                "th, td { border: 1px solid #ddd; padding: 8px 16px; }\n" +
                "th { background-color: #f2f2f2; }\n" +
                "</style>\n" +
                "</head>\n" +
                "<body>\n" +
                htmlContent +
                "</body>\n" +
                "</html>";
    }

    /**
     * 将HTML转换为PDF
     */
    private static void convertHtmlToPdf(String htmlContent, String pdfFilePath) throws Exception {
        try (OutputStream os = new FileOutputStream(pdfFilePath)) {
            ITextRenderer renderer = new ITextRenderer();
            // 可以在这里设置字体，解决中文显示问题
            // renderer.getFontResolver().addFont("path/to/font.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            renderer.setDocumentFromString(htmlContent);
            renderer.layout();
            renderer.createPDF(os);
        }
    }

    // 测试方法
    public static void main(String[] args) {
        try {
            // 输入的Markdown文件路径
            String markdownFile = "src/main/java/mysql/innoDB/摘要-MySql技术内幕 InnoDB存储引擎.md";
            // 输出的PDF文件路径
            String pdfFile = "src/main/java/mysql/innoDB/摘要-MySql技术内幕 InnoDB存储引擎.pdf";

            convert(markdownFile, pdfFile);
            System.out.println("转换成功：" + pdfFile);
        } catch (Exception e) {
            System.err.println("转换失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
}
